package com.cskaoyan.service.wxservice.impl;

import com.cskaoyan.bean.chaosbean.cart.bo.WxCartAddBo;
import com.cskaoyan.bean.chaosbean.cart.bo.WxCartFastAddBo;
import com.cskaoyan.bean.chaosbean.cart.bo.WxCartUpdateBo;
import com.cskaoyan.bean.chaosbean.cart.vo.CartIndexVO;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.wxservice.CartWechatService;
import com.cskaoyan.util.SubjectUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 楚夏三分
 * @datetime 2023/1/2 16:37
 * @description: TODO:
 */
@Service
public class CartWechatServiceImpl implements CartWechatService {
    @Autowired
    MarketCartMapper cartMapper;
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketAddressMapper addressMapper;
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCouponUserMapper userCouponMapper;
    @Autowired
    MarketGrouponRulesMapper grouponRulesMapper;
    @Autowired
    MarketSystemMapper systemMapper;
    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;



    @Override
    public CartIndexVO index() {
        // 伪造id
        // Integer userId = getUserId();
        // 这里能成功吗?
        Subject subject = SecurityUtils.getSubject();
        MarketUser marketUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer userId = marketUser.getId();

        // 查询VO中的cartList
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andUserIdEqualTo(userId);
        List<MarketCart> marketCartsList = cartMapper.selectByExample(marketCartExample);
        // 查询VO中的cartTotal
        int goodsCount = marketCartsList.stream().mapToInt(MarketCart::getNumber).sum();
        int checkedGoodsCount = marketCartsList.stream().filter(MarketCart::getChecked).mapToInt(MarketCart::getNumber).sum();
        BigDecimal goodsAmount = marketCartsList.stream()
                .map(marketCart -> marketCart.getPrice().multiply(BigDecimal.valueOf(marketCart.getNumber())))
                .reduce(BigDecimal.ZERO,BigDecimal::add);
        BigDecimal checkedGoodsAmount = marketCartsList.stream().filter(MarketCart::getChecked)
                .map(marketCart -> marketCart.getPrice().multiply(BigDecimal.valueOf(marketCart.getNumber())))
                .reduce(BigDecimal.ZERO,BigDecimal::add);

        // 封装VO
        CartIndexVO cartIndexVO = new CartIndexVO();
        CartIndexVO.CartTotalBean cartTotalBean = new CartIndexVO.CartTotalBean(goodsCount,checkedGoodsCount,goodsAmount,checkedGoodsAmount);
        cartIndexVO.setCartList(marketCartsList);
        cartIndexVO.setCartTotal(cartTotalBean);

        return cartIndexVO;
    }

    @Override
    public void addCart(WxCartAddBo wxCartAddBo) {
        // 从BO中取出对应参数
        Integer goodsId = wxCartAddBo.getGoodsId();
        Short number = wxCartAddBo.getNumber();
        Integer productId = wxCartAddBo.getProductId();
        // 获取商品PO
        MarketGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
        // 创建购物车PO
        MarketCart marketCart = new MarketCart();

        // Shrio获取当前用户的id
        // Subject subject = SecurityUtils.getSubject();
        // MarketUser principal = (MarketUser) subject.getPrincipal();
        // Integer userId = principal.getId();

        // 伪代码取固定值
        Integer userId = 1;

        marketCart.setUserId(userId);
        marketCart.setGoodsId(goodsId);
        marketCart.setGoodsSn(goods.getGoodsSn());
        marketCart.setGoodsName(goods.getName());
        marketCart.setProductId(productId);
        // 零售价格
        marketCart.setPrice(goods.getRetailPrice());
        marketCart.setNumber(number);

        // Specifications
        MarketGoodsSpecificationExample example = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsIdEqualTo(goodsId);
        List<MarketGoodsSpecification> specificationsList = specificationMapper.selectByExample(example);

        // Gson gson = new Gson();

        List<String> list = specificationsList.stream()
                .map(MarketGoodsSpecification::getValue)
                .collect(Collectors.toList());

        String[] strings = list.toArray(new String[0]);

        marketCart.setSpecifications(strings);
        marketCart.setChecked(true);
        marketCart.setPicUrl(goods.getPicUrl());
        marketCart.setAddTime(new Date());
        marketCart.setUpdateTime(new Date());
        marketCart.setDeleted(false);
        //执行插入
        cartMapper.insertSelective(marketCart);
    }

    @Override
    public int getGoodsCount() {
        //获取当前用户的id
        // Subject subject = SecurityUtils.getSubject();
        // MarketUser principal = (MarketUser) subject.getPrincipal();
        // Integer userId = principal.getId();
        Integer userId = 1;

        MarketCartExample example = new MarketCartExample();
        MarketCartExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<MarketCart> marketCarts = cartMapper.selectByExample(example);
        //计算总数
        int sum = marketCarts.stream().mapToInt(MarketCart::getNumber).sum();

        return sum;
    }

    @Override
    public Integer fastAdd(WxCartFastAddBo wxCartFastAddBo) {
        //有二种情况第一种购物车中没有此商品则添加到购物车，第二种有此商品执行更改商品的数量
        //获取当前用户的id
        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();
        Integer userId = principal.getId();
        //实例化对象
        MarketCartExample example = new MarketCartExample();
        //增加条件查询
        MarketCartExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andGoodsIdEqualTo(wxCartFastAddBo.getGoodsId());
        criteria.andProductIdEqualTo(wxCartFastAddBo.getProductId());
        List<MarketCart> marketCarts = cartMapper.selectByExample(example);
        if (marketCarts.size() == 0) {
            //此时是第一种购物车中没有此商品则添加到购物车
            WxCartAddBo wxCartAddBo = new WxCartAddBo(wxCartFastAddBo.getGoodsId(), wxCartFastAddBo.getNumber(), wxCartFastAddBo.getProductId());
            //加入购物车
            addCart(wxCartAddBo);
        } else {
            //此时是第二种有此商品执行更改商品的数量
            WxCartUpdateBo wxCartUpdateBo = new WxCartUpdateBo(wxCartFastAddBo.getProductId(), wxCartFastAddBo.getGoodsId(), wxCartFastAddBo.getNumber(), null);
            update(wxCartUpdateBo);
        }
        //还要获得此购物车信息的id
        List<MarketCart> realMarketCarts = cartMapper.selectByExample(example);
        MarketCart realMarketCart = realMarketCarts.get(0);
        //购物车信息的id
        Integer marketCartId = realMarketCart.getId();
        return marketCartId;
    }

    @Override
    public void update(WxCartUpdateBo cartUpdateBo) {
        //获取要修改的购物车信息
        Integer id = cartUpdateBo.getId();
        if (id != null) {
            //此时是在购物车修改操作
            //获取此购物车记录
            MarketCart marketCart = cartMapper.selectByPrimaryKey(id);
            //修改商品数量和商品的规格
            marketCart.setNumber(cartUpdateBo.getNumber());
            marketCart.setProductId(cartUpdateBo.getProductId());
            //修改数据库中购物车记录
            cartMapper.updateByPrimaryKeySelective(marketCart);
        } else {
            //此时是快速购买中修改购物车中商品数量的操作
            //获取当前用户的id
            Subject subject = SecurityUtils.getSubject();
            MarketUser principal = (MarketUser) subject.getPrincipal();
            Integer userId = principal.getId();
            //实例化对象
            MarketCartExample example = new MarketCartExample();
            //增加条件查询
            MarketCartExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andGoodsIdEqualTo(cartUpdateBo.getGoodsId());
            criteria.andProductIdEqualTo(cartUpdateBo.getProductId());
            List<MarketCart> marketCarts = cartMapper.selectByExample(example);
            //获取要修改的购物车信息
            MarketCart marketCart = marketCarts.get(0);
            //修改商品的数量(直接替换掉数据库中购物车规格数量)
            marketCart.setNumber(cartUpdateBo.getNumber());
            //对数据库修改
            cartMapper.updateByPrimaryKeySelective(marketCart);
        }
    }

    /**
     * 取出当前登录信息并返回用户ID
     */
    private static Integer getUserId() {
        // 伪造id
        // return 1;
        // Shrio的Subject主体获取id
        return Objects.requireNonNull(SubjectUtil.getUserInfo(new MarketUser())).getId();
    }
}





